import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";
import viteCompression from "vite-plugin-compression";
// svg
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
// 按需引入
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
// mock
import { viteMockServe } from "vite-plugin-mock";

// https://vitejs.dev/config/
export default defineConfig((config) => {
  const { command, mode } = config;
  const env = loadEnv(mode, process.cwd(), "");
  console.log(env.VITE_APP_TITLE);

  return {
    base: "./",
    plugins: [
      vue(),
      viteMockServe({
        // 只在开发阶段开启 mock 服务
        localEnabled: command === "serve",
      }),
      // gzip压缩 生产环境生成 .gz 文件
      viteCompression({
        verbose: true,
        disable: false,
        threshold: 10240,
        algorithm: "gzip",
        ext: ".gz",
      }),
      // * 使用 svg 图标
      createSvgIconsPlugin({
        // 指定需要缓存的图标文件夹
        iconDirs: [path.resolve(process.cwd(), "src/icons/svg")],
        // 指定symbolId格式
        symbolId: "icon-[dir]-[name]",
      }),
      // 按需引入
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
    ],
    resolve: {
      alias: {
        "@": path.resolve(__dirname, "src"),
      },
    },
    css: {
      // css预处理器
      preprocessorOptions: {
        less: {
          charset: false,
          math: "always", // 括号内才使用数学计算
          globalVars: {
            // 全局变量 可以抽离
            mainColor: "red",
          },
          additionalData: '@import "@/common/theme/common.less";', // 全局样式
        },
      },
    },
    // 生产环境打包配置，去除 console debugger
    build: {
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
    },
  };
});
